import { defineStore } from "pinia";

export const useRoutesStore = defineStore(
  "routesStore",
  () => {
    const routes = ref({
      nowRoute: <any>{},
      routes: <Array<any>>[],
    });

    // 添加历史路由
    function addRoute(route: any) {
      console.log("addRoutes", route);

      // 判断是否登录页面
      if (route.meta?.title !== "登录/注册") {
        // 判断是否重复
        const isDuplicate = routes.value.routes.some(
          (item) => item.meta?.title === route.meta?.title
        );
        if (!isDuplicate) {
          routes.value.nowRoute = route;
          routes.value.routes.push(route);
        } else {
          console.log("路由已存在，未添加:", route.meta?.title);
        }
      }

      routes.value.nowRoute = route;
    }

    // 移除历史路由
    function removeRoute(routeName: any) {
      // 当只有一个路由时，不允许移除
      if (routes.value.routes.length === 1) {
        return;
      }

      // 找到要移除的路由的索引
      const removeIndex = routes.value.routes.findIndex(
        (item) => item.meta?.title === routeName
      );

      // 找到当前路由的索引
      const nowIndex = routes.value.routes.findIndex(
        (item) => item.meta?.title === routes.value.nowRoute.meta?.title
      );

      if (removeIndex === nowIndex) {
        // 移除历史路由后，重新设置当前路由
        if (removeIndex !== -1) {
          if (removeIndex === 0) {
            routes.value.nowRoute = routes.value.routes[1];
          } else {
            routes.value.nowRoute = routes.value.routes[removeIndex - 1];
          }
        }
      }

      // 移除路由
      routes.value.routes = routes.value.routes.filter(
        (item) => item.meta?.title !== routeName
      );
    }

    // 重置路由
    function resetRoutes() {
      routes.value.nowRoute = {};
      routes.value.routes = [];
    }

    return { routes, addRoute, removeRoute, resetRoutes };
  } /* ,
  { persist: true } */
);
